package com.wodogs.utils.tools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileUtils {

	public static void saveToDisk(String file_url,String dirPath,String fileName) {
        // 获取输入流
		if(file_url.startsWith("//")){
			file_url = "http:"+file_url;
		}
        InputStream inputStream = getInputStream(file_url);
 
        byte[] date = new byte[1024];
        int len = 0;
        FileOutputStream fileOutputStream = null;
        
        File dir = new File(dirPath);
        if(!dir.exists()){
        	dir.mkdirs();
        }
        try {
        	fileOutputStream = new FileOutputStream(dirPath+"/"+fileName);
        	
        	while ((len = inputStream.read(date)) != -1) {
        		fileOutputStream.write(date, 0, len);
        	}
        } catch (IOException e) {
        	// TODO Auto-generated catch block
        	e.printStackTrace();
        } finally {
        	
        	try {
        		if (inputStream != null) {
        			inputStream.close();
        		}
        		if (fileOutputStream != null) {
        			fileOutputStream.close();
        		}
        	} catch (IOException e) {
        		// TODO Auto-generated catch block
        		e.printStackTrace();
        	}
        }
 
    }
	
	public static InputStream getInputStream(String file_url) {
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;
 
        try {
            URL url = new URL(file_url);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            // 设置连接网络的超时时间
            httpURLConnection.setConnectTimeout(3000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("GET");
 
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == 200) {
                inputStream = httpURLConnection.getInputStream();
 
            }
 
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
 
        return inputStream;
    }
}
